<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle"
               @onCollapse="collapseHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams2"
      isSelectColumn
      datakey="records"
      isExportExcel2
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button size="small" :disabled="boSwitch" type="primary" icon="el-icon-edit" @click="openCloseBO(null,0)">批量申请关闭</el-button>
        <el-button size="small" type="primary" icon="el-icon-edit" @click="visibleImportYjdhrq = true">导入</el-button>
        <el-button size="small" :disabled="editSwitch" type="primary" icon="el-icon-edit"
                   @click="editHandle">修改
        </el-button>
      </template>
    </FilterTable>

    <BaseDialog :visible.sync="visibleForm"  title="修改预计到货时间" destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditForm :handleType="handleType" :pageType="pageType" :value="rowSelectData" @close="closeHandler"/>
    </BaseDialog>

    <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportYjdhrq" width="80vw" title="预计到货时间批量导入"
                destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }">
      <ExcelImport
        ref="import"
        template-file-name="导入模板.xlsx"
        :importRules="importRules"
        :onBeforeDownloadTemp="onBeforeDownloadTemp"
        :onComplete="importComplete"
        @close="visibleImportYjdhrq = false"
      />
    </BaseDialog>

    <BaseDialog
      :visible.sync="issearch"
      :title="'服务商查询'"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ownerSeacher @close="dealercloseHandler" />
    </BaseDialog>

    <BaseDialog  :visible.sync="closeForm" title="BO申请关闭" destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <closeForm :value="rowSelectData" @close="closeBOHandler"/>
    </BaseDialog>
  </div>
</template>

<script>
import {getBOOrderList, postUpdateStatus, putImportYJDHSJ} from '@/api/partsmanage/purchaseManage/purchaseSubmit';
import {dictionary} from '@/utils/dictMixin';
import EditForm from './editForm';
import closeForm from './closeForm';
import ExcelImport from '@/components/ExcelImport';
import {dateFormat} from '@/utils';
import ownerSeacher from '@/pages/partsmanage/claim/approve/ownerSeacher';
import moment from "moment";
import { notifyAction } from '@/utils';


export default {
  name: "BO_OEM_Query",
  components: {
    EditForm,
    ExcelImport,
    closeForm,
    ownerSeacher
  },
  mixins: [dictionary],
  data() {
    return {
      issearch: false,
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      importRules: this.initImportRuleFun(),
      fetchApi: getBOOrderList,
      pageType: 'OEM_Query', //查询页面类型 cancelApply：BO取消申请 ，query：BO查询页面
      fetchParams: {
        xhrAbort: true
      },
      visibleForm: false,
      visibleImportYjdhrq: false,
      handleType: 'add',
      formData: {},
      // dialogTitle: '配件采购提报',
      initData: {},
      rowSelectData: [],
      closeForm: false,
      editSwitch:true,
      boSwitch:true
    };
  },
  computed: {
    fetchParams2() {
      return {
        pageType: this.pageType,
        ...this.fetchParams
      }
    }
  },
  async created() {
    // this.fetchParams.submStartDate = moment().subtract(7,'days').format('YYYY-MM-DD');
    // this.fetchParams.submEndDate = moment().format('YYYY-MM-DD');
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '服务商代码',
          fieldName: 'dealerCode',
          initialValue: '',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          }
        },
        {type: 'INPUT', label: '服务商简称', fieldName: 'dealerName'},
        {type: 'INPUT', label: '订购单号', fieldName: 'xsddhm'},
        {type: 'INPUT', label: '备件代码', fieldName: 'bjxmbh'},
        {type: 'INPUT', label: '备件名称', fieldName: 'bjzwmc'},
        {type: 'SELECT',  initialValue:30031001,label: '订单类型', fieldName: 'xsddlx', placeholder: '请选择', itemList: this.createDictList('3003')},
        {type: 'SELECT',clearable:false, initialValue:30181001, label: 'BO备件状态', fieldName: 'xsddzt', placeholder: '请选择', itemList: this.createDictList('3018')},
        {
          type: 'RANGE_DATE',
          fieldName: 'submStartDate|submEndDate',
          label: '提报日期',
          dateType: 'daterange',
          valueFormat: 'yyyy-MM-dd',
          clearable:false,
          // initialValue: [
            // moment().subtract(7,'days').format('YYYY-MM-DD'),
            // moment().format('YYYY-MM-DD')
          // ],
        },
      ]
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: params => {
            return (
              <div>
                <el-button disabled={params.row.partOrder.boddzt != 30181001}  type="text" size="mini" onClick={() => this.openCloseBO(params.row,1)}>
                  BO申请关闭
                </el-button>
              </div>
            );
          }
        },
        { title: '服务商代码', dataIndex: 'partOrder.dealerCode', sorter: true },
        { title: '服务商简称', dataIndex: 'partOrder.dealerName', sorter: true },
        { title: '订购单号', width: 180, dataIndex: 'partOrder.xsddhm', sorter: true },
        { title: '订单类型', dataIndex: 'partOrder.xsddlx', sorter: true, dictItems: this.createDictList('3003') },
        { title: '备件代码', width: 180, dataIndex: 'partInfo.bjxmbh', sorter: true },
        { title: '备件名称', dataIndex: 'partInfo.bjzwmc', sorter: true },
        { title: '物料组', dataIndex: 'partInfo.material', sorter: true , dictItems: this.createDictList('3054') },
        { title: 'BO备件状态', dataIndex: 'partOrder.boddzt', sorter: true, dictItems: this.createDictList('3018') },
        { title: '订购数量', dataIndex: 'bstxsl', sorter: true },
        { title: '发运数量', dataIndex: 'bjfysl', sorter: true },
        { title: '审批数量', dataIndex: 'bsspsl', sorter: true },
        { title: 'BO数量', dataIndex: 'bsbosl', sorter: true },
        { title: '关闭数量', dataIndex: 'qxsl', sorter: true },
        { title: '订单提报时间', dataIndex: 'partOrder.ddtbsj', sorter: true, filter: true },
        { title: '关闭时间', dataIndex: 'boqrsj', sorter: true, filter: true },
        { title: '预计到货日期', dataIndex: 'yjdhsj', dateFormat: 'yyyy-MM-dd', sorter: true, filter: true },
        { title: '跟进结果', dataIndex: 'bsgjjg' },
        { title: '解决途径', dataIndex: 'bsjjtj' }
      ]
    },
    initImportRuleFun() {
      return [
        {prop: 'dealerCode', title: '服务商代码'},
        {prop: 'dealerName', title: '服务商简称'},
        {
          prop: 'xsddhm', title: '订购单号',
          rule: {required: true, message: '订购单号不能为空'}
        },
        {
          prop: 'bjxmbh', title: '备件代码',
          rule: {required: true, message: '备件代码不能为空'},
        },
        {prop: 'bjzwmc', title: '备件名称'},
        {
          prop: 'yjdhsj', title: '预计到货日期',
          rule: [
            {required: false, message: '预计到货日期必填'},
            {
              dateFormat: 'yyyy-MM-dd',
              validator: (callback, rule, val, row) => {
                if(!val) return callback();
                try {
                  const date = new Date(val);
                  if (date.toDateString() !== 'Invalid Date') {
                    row.yjdhsj = dateFormat('yyyy-MM-dd', date)
                    callback()
                  } else {
                    callback(new Error('预计到货日期格式不对'))
                  }
                } catch (e) {
                  callback(new Error('预计到货日期格式不对'))
                }
              }
            }
          ]
        },
        { prop: 'bsgjjg', title: '跟进结果', },
        { prop: 'bsjjtj', title: '解决途径', }
      ]
    },
    async onBeforeDownloadTemp(callback) {
      const data = [
        {dealerCode:"PKXXX",dealerName:"XXX服务商",xsddhm:"CGXXXX",bjxmbh:"FDJ",bjzwmc:"XXX发动机",yjdhsj:"2022-01-01",bsgjjg:"备货中",bsjjtj:"联系工厂"}
      ]
      callback(data);
    },
    //导入
    importComplete(datas, callback) {
      const errorData = []
      datas.forEach((item, index1) => {
        const indexarr = []
        datas.forEach((i, index2) => {
          if (
            i.xsddhm === item.xsddhm &&
            i.bjxmbh === item.bjxmbh &&
            i.bjpjsx === item.bjpjsx &&
            i.bsddhh === item.bsddhh &&
            index1 !== index2) {
            indexarr.push(index2 + 1)
          }
        })
        if (indexarr.length) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `BO订单信息和${indexarr.join(',')}行重复`
          })
        }
      })
      if (errorData.length) {
        callback(errorData)
      } else {
        putImportYJDHSJ(datas).then(res => {
          if(res.resultCode == 200) {
            if(res.data.status){
              this.visibleImportYjdhrq = false
              this.$notify.success({title: '提示信息', message: '批量导入成功'});
              callback()
              this.closeHandler('refresh')
            }else{
              callback(res.data.errorData)
            }
          } else {
            callback([{errormsg: '服务器运行异常'}])
          }
        })
      }
    },
    editHandle() {
      this.handleType = 'edit';
      this.visibleForm = true
    },
    cancleHandle(row, xsddzt) {
      this.$confirm('您确定要取消吗？取消之后您不可再次操作！', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await postUpdateStatus({
          id: row.id,
          xsddzt
        })
        if (res.resultCode == 200) {
          this.$notify.success({title: '提示信息', message: '取消成功'});
          // 重新加载
          this.fetchParams = Object.assign({}, this.fetchParams);
        }
      }).catch(() => {
      });
    },
    closeHandler(type) {
      this.visibleForm = false
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    selectChange(val) {
      console.log(val);
      this.rowSelectData = val;
      if(val != null && val.length >0 ){
        let mark = 0;
        // let markTwo = 0;
        // let partNo = val[0].partOrder.xsddhm
        val.forEach(row =>{
          if(row.partOrder.boddzt == 30181005){//当前选中的BO单已有关闭的单子则不允许修改
            mark = 1;
          }
          // if(partNo != row.partOrder.xsddhm){//只能选择同一备件订单下的BO单
          //   markTwo = 1;
          // }
        })
        if(mark == 1){
            this.editSwitch = true;
        }else{
            this.editSwitch = false;
        }
        // if(markTwo == 1){
        //     this.boSwitch = true;
        // }else{
            this.boSwitch = false;
        // }
      }else{
        this.editSwitch = true;
        this.boSwitch = true;
      }
    },
    changeHandle(val) {
      console.log(val);
      if(val.submStartDate != undefined && val.submStartDate != null){
        val.submStartDate = moment(new Date(val.submStartDate)).format('YYYY-MM-DD')+" 00:00:00";
      }
      if(val.submEndDate != undefined && val.submEndDate != null){
         val.submEndDate = moment(new Date(val.submEndDate)).format('YYYY-MM-DD')+" 23:59:59";
      }
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    seacherFun() {
      this.issearch = true
    },
    dealercloseHandler(val) {
      console.info(val)
      if(val) {
        this.topFilterList.find(x => x.fieldName == 'dealerCode').initialValue = val.dealerCode;
        this.topFilterList.find(x => x.fieldName == 'dealerName').initialValue = val.dealerShortname;
      }
      this.issearch = false;
    },
    openCloseBO(val,type) {
      console.log(val);
      if(type == 1){//单条
        let data = [];
        data.push(val)
        this.rowSelectData = data;
      }
      let markTwo = 0;

      let partNo = this.rowSelectData[0].partOrder.xsddhm
      this.rowSelectData.forEach(row =>{

          if(partNo != row.partOrder.xsddhm){//只能选择同一备件订单下的BO单
            markTwo = 1;
          }
      })

      if(markTwo == 1){
        notifyAction('只能选择同一备件订单下的BO单!', 'warning');
        return;
      }
      this.handleType = 'edit';
      this.closeForm = true;
    },
    closeBOHandler(type) {
      this.closeForm = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    }
  }
}
</script>

<style scoped>

</style>
